package com.thx.file;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import com.thx.common.util.FileUtil;
import com.thx.file.util.WebFileUtil;

public class IoUtil
{
  static final Pattern RANGE_PATTERN = Pattern.compile("bytes \\d+-\\d+/\\d+");
  protected final Logger logger = Logger.getLogger(getClass());
 /*保存文件至数据库*/
  public static  com.thx.file.model.File saveFile(File file,String oldFileName){
	  com.thx.file.model.File f = WebFileUtil.saveFile(file,oldFileName);
	  if(f!=null){
		 f.setFileBytes(file.length());
		 return f;
	  }
	 return null;
  }
  //新建一个以时间命名的文件
  public static File getFile(String filename,String modPath) throws IOException
  {
    if ((filename == null) || (filename.isEmpty()))
      return null;
    String newFileName = FileUtil.rename(filename);/*文件以时间拼串重命名*/
    String name = newFileName.replaceAll("/", Matcher.quoteReplacement(File.separator));
    String path = WebFileUtil.getFilePath(modPath)+File.separator+name;
    File f = new File(path);
    if (!f.getParentFile().exists())
      f.getParentFile().mkdirs();
    if (!f.exists()) {
      f.createNewFile();
    }
    return f;
  }
  //得到token文件
  public static File getTokenedFile(String key,String modPath) throws FileNotFoundException
  {
    if ((key == null) || (key.isEmpty())) {
      return null;
    }
    String path = WebFileUtil.getFilePath(modPath)+File.separator+key;
    File f = new File(path);
    if (!f.getParentFile().exists())
      f.getParentFile().mkdirs();
    if (!f.exists()) {
      throw new FileNotFoundException("File `" + f + "` not exist.");
    }
    return f;
  }
//生成token文件
  public static void storeToken(String key,String modPath) throws IOException {
    if ((key == null) || (key.isEmpty())) {
      return;
    }
    String path = WebFileUtil.getFilePath(modPath)+File.separator+key;
    File f = new File(path);
    if (!f.getParentFile().exists())
      f.getParentFile().mkdirs();
    if (!f.exists())
      f.createNewFile();
  }

  public static void close(Closeable stream)
  {
    try{
      if (stream != null)
        stream.close();
    }
    catch (IOException e){
    }
  }
 /* html5上传时，解析从客户端传来的_xhr.setRequestHeader("Content-Range", range);
  包含需上传文件的开始端、结束端、文件总大小*/
  public static Range parseRange(HttpServletRequest req)
    throws IOException{
    String range = req.getHeader("content-range");//bytes 20971520-31457280/1507455946
    Matcher m = RANGE_PATTERN.matcher(range);
    if (m.find()) {
      range = m.group().replace("bytes ", "");
      String[] rangeSize = range.split("/");
      String[] fromTo = rangeSize[0].split("-");
      long from = Long.parseLong(fromTo[0]);
      long to = Long.parseLong(fromTo[1]);
      long size = Long.parseLong(rangeSize[1]);
      return new Range(from, to, size);
    }
    throw new IOException("Illegal Access!");
  }
  public static com.thx.file.model.File streaming(InputStream in, String key, String fileName,String modPath)
   throws IOException{
		OutputStream out = null;
		File f = getTokenedFile(key,modPath);
	    com.thx.file.model.File dataFile;
		try {
		   out = new FileOutputStream(f);
           int read = 0;
		   byte[] bytes = new byte[10485760];
		   while ((read = in.read(bytes)) != -1) {
		      out.write(bytes, 0, read);
		   }
		   out.flush();
		    } finally {
		     close(out);
		   }
        File dst = getFile(fileName,modPath);
		dst.delete();
		f.renameTo(dst);
		dataFile = saveFile(dst,fileName);
		return dataFile;
	 }
}